// 入库表 bootstrap设置
$("#inbound").bootstrapTable({
    url: "/inbound/list",
    method: "get",
    pagination: true,   //是否显示分页（*）
    pageSize: 10,       //每页的记录行数（*）
    pageList: [10, 20, 50, 100, 'All'], //可供选择的每页的行数（*）
    sidePagination: "client",    //分页方式：client客户端分页，server服务端分页（*）
    pageNumber: 1,
    classes: "table table-bordered table-striped table-condensed table-hover",                  //初始化加载第一页，默认第一页
    columns: [{
        title: "入库id",
        field: "id",
        visible: false
    }, {
        title: "入库编号",
        field: "no",
    }, {
        title: "商品名称",
        field: "goodsName",
    }, {
        title: "入库数量（盒/箱）",
        field: "boxNum",
    }, {
        title: "供应商名称",
        field: "supplierName",
    }, {
        title: "入库成本：元",
        field: "priceYuan",
    }, {
        title: "入库数量",
        field: "num",
    }, {
        title: "备注",
        field: "note",
    }, {
        title: "入库时间",
        field: "createTime",
    }, {
        field: 'operate',
        title: '操作',
        align: 'center',
        valign: 'middle',
        width: 200,
        events: {
            'click #update': function (e, value, row, index) {
                $('#update-id').val(row.id);
                $('#update-no').val(row.no);
                $('#update-goodsId').val(row.goodsId);
                $('#update-goodsName').val(row.goodsName);
                $('#update-num').val(row.num);
                $('#update-boxNum').val(row.boxNum);
                $('#update-perBox').val(row.perBox);
                $('#update-priceYuan').val(row.priceYuan);
                $('#update-supplierId').val(row.supplierId);
                $('#update-supplierName').val(row.supplierName);
                $('#update-note').val(row.note);
            },
            'click #delete': function (e, value, row, index) {
                $('#delete-id').val(row.id);
                $('#delete-no').val(row.no);
                $('#delete-goodsId').val(row.goodsId);
                $('#delete-goodsName').val(row.goodsName);
                $('#delete-num').val(row.num);
                $('#delete-supplierId').val(row.supplierId);
                $('#delete-supplierName').val(row.supplierName);
                $('#delete-note').val(row.note);
            }
        },
        formatter: function (value, row, index) {
            let result = "";
            result += '<button id="update" class="btn btn-info" data-toggle="modal" data-target="#updateModal">编辑</button>';
            result += '<button id="delete" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal" style="margin-left:10px;width: 50px;height=25px;font-size: 15px">删除</button>';
            return result;
        }
    }]
});

$("#search-startAndEndTime").daterangepicker({
    locale: {
        "format": 'YYYY-MM-DD HH:mm:ss',
        "separator": " - ",
        "applyLabel": "确定",
        "cancelLabel": "取消",
        "resetLabel": "重置",
        "fromLabel": "起始时间",
        "toLabel": "结束时间'",
        "customRangeLabel": "自定义",
        "weekLabel": "W",
        "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"],
        "monthNames": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        "firstDay": 1
    },
    ranges: {
        '今日': [moment(), moment()],
        '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        '最近7日': [moment().subtract(6, 'days'), moment()],
        '最近30日': [moment().subtract(29, 'days'), moment()],
        '本月': [moment().startOf('month'), moment().endOf('month')],
        '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
        '今年': [moment().startOf('year'), moment().endOf('year')],
    },
    "alwaysShowCalendars": true,
    "startDate": moment().subtract(1, 'years'),  //1年前
    // "startDate": new Date(),
    "endDate": new Date(),
    "opens": "right",
}, function (start, end, label) {
});

//查询入库 点击事件
function searchInboundOnClick() {
    let startAndEndTime = $("#search-startAndEndTime").val().replace(/\s-\s/ig, '?').split('?');
    $.get({
        url: "/inbound/list",
        data: {
            no: $("#search-no").val(),
            goodsName: $("#search-goodsName").val(),
            supplierName: $("#search-supplierName").val(),
            startDateTime: startAndEndTime[0],
            endDateTime: startAndEndTime[1]
        },
        dataType: "json",
        success: function (data) {
            $("#inbound").bootstrapTable('load', data);
        }
    });
}

//按下Enter查询
$(document).keyup(function (event) {
    if (event.keyCode == 13){
        searchInboundOnClick();
    }

});

$("#reset").click(function () {
    $("#search-goodsName").val("");
    $("#search-supplierName").val("");
    $("#search-startAndEndTime").val("");
    $("#search-no").val("");
})

//新增时输入盒装数量，修改散装数量
function boxNumInput(tObject) {
    let tr = $(tObject).parent();
    let boxNum = $(tObject).children("input").val();
    let perBox = tr.children('[name= "perBox"]').eq(0).text();
    tr.children('[name= "num"]').eq(0).html(boxNum * perBox);
}


//新增时输入盒装数量，修改散装数量
function numInput(tObject) {
    let tr = $(tObject).parent();
    let num = $(tObject).children("input").val();
    let perBox = tr.children('[name= "perBox"]').eq(0).text();
    tr.children('[name= "boxNum"]').eq(0).html(num / perBox);
}

//新增时输入散装数量，修改盒装数量


//新增入库 点击事件
$("#addInbound").click(function () {
    let params = getAddInboundList();
    $.post({
        url: "/inbound/addList",
        async: false,//同步，默认是true，异步
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(params),
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchInboundOnClick();
    $("#addModal").modal('hide');
});

//修改入库 点击事件
$("#updateInbound").click(function () {
    $.post({
        url: "/inbound/update",
        async: false,//同步，默认是true，异步
        data: {
            id: $("#update-id").val(),
            goodsId: $("#update-goodsId").val(),
            num: $("#update-num").val(),
            supplierId: $("#update-supplierId").val(),
            note: $("#update-note").val(),
        },
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchInboundOnClick();
    $("#updateModal").modal('hide');
});

$("#update-num").on("input", function () {
    let perNum = $("#update-perBox").val() == null ? 1 : $("#update-perBox").val();
    $("#update-boxNum").val($("#update-num").val() / perNum);
});

$("#update-boxNum").on("input", function () {
    let perNum = $("#update-perBox").val() == null ? 1 : $("#update-perBox").val();
    $("#update-num").val($("#update-boxNum").val() * perNum);
});
//删除入库 点击事件
$("#deleteInbound").click(function () {
    $.post({
        url: "/inbound/delete",
        async: false,//同步，默认是true，异步
        data: {
            id: $("#delete-id").val(),
        },
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchInboundOnClick();
    $("#deleteModal").modal('hide');
});


//根据条件弹出符合条件的供应商名称
$("#add-all-supplierName").attr("oninput", "getAddSupplierData(this)")

//修改时 点击供应商信息输入框，模糊查询商品列表并展示
$("#update-supplierName").on("input", getUpdateSupplierData);

//获得整个商品列表的数据，包装为参数 数组格式
function getAddInboundList() {
    let table = $("#addGoodsTable");
    let tbody = table.children();
    let trs = tbody.children();
    let inboundList = [];
    for (let i = 1; i < trs.length; i++) {
        let tr = trs.eq(i);
        let inbound = {};
        inbound.goodsId = tr.children('[name= "goodsId"]').eq(0).text();
        inbound.goodsName = tr.children('[name= "goodsName"]').eq(0).text();
        inbound.num = tr.children('[name= "num"]').eq(0).text();
        inbound.supplierId = tr.children('[name= "supplierId"]').eq(0).text();
        inbound.supplierName = tr.children('[name= "supplierName"]').eq(0).text();
        inbound.priceCent = tr.children('[name= "priceYuan"]').eq(0).text() * 100;
        inbound.note = tr.children('[name= "note"]').eq(0).text();
        inboundList.push(inbound);
    }
    return inboundList;
}

//商品信息表格，每个位置点击时 当前行出现输入框
function tdClick(tdObject) {
    let td = $(tdObject);
    td.attr("onclick", "");
    //1,取出当前td中的文本内容保存起来
    let text = td.text();
    //2,清空td里面的内容
    td.html(""); //也可以用td.empty();
    //3，建立一个文本框，也就是input的元素节点
    let input = $("<input>");
    //4，设置文本框的值是保存起来的文本内容
    input.width(td.width());
    input.attr("value", text);
    //输入框 移除焦点事件
    input.bind("blur", function () {
        let inputNode = $(this);
        let inputText = inputNode.val();
        let tdNode = inputNode.parent();
        tdNode.html(inputText);
        tdNode.click(tdClick);
        td.attr("onclick", "tdClick(this)");
    });
    //按下 Enter 的处理
    input.keyup(function (event) {
        let myEvent = event || window.event;
        let keyCode = myEvent.keyCode;
        if (keyCode == 13) {
            let inputNode = $(this);
            let inputText = inputNode.val();
            let tdNode = inputNode.parent();
            tdNode.html(inputText);
            tdNode.click(tdClick);
        }
    });
    //5，将 输入框和模糊搜索框 加入到td中
    let ul = $("<ul>");
    switch (td.attr("name")) {
        case "goodsName":
            ul.attr("id", "add-goods-dropdown-menu");
            ul.attr("class", "dropdown-menu pre-scrollable");
            input.attr("id", "add-goodsName");
            input.attr("oninput", "getAddGoodsData(this)");
            break;
        case "supplierName":
            ul.attr("id", "add-supplier-dropdown-menu");
            ul.attr("class", "dropdown-menu pre-scrollable");
            input.attr("id", "add-supplierName");
            input.attr("oninput", "getAddSupplierData(this)");
            break;
    }


    td.append(input);
    let t = input.val();
    input.val("").focus().val(t);

    td.append(ul);
    //6,清除点击事件
    td.unbind("click");
    //在当前节点点击 不失去焦点
    td.on('mousedown', function () {
        event.preventDefault();
    });
}


//新增时 商品列表当前行数
let row = 0;

//新增一行
function addTr() {
    row++;
    let table = $("#addGoodsTable");
    let tr = $("<tr>"
        //商品id
        + "<td style='text-align: center;' name='goodsId'>" + "</td>"
        //商品名称
        + "<td style='text-align: center;' onclick='tdClick(this)' name='goodsName' autocomplete='off'>" + "</td>"
        //盒装数量
        + "<td style='text-align: center;' onclick='tdClick(this)' name='boxNum' oninput='boxNumInput(this)'>" + "</td>"
        //散装数量
        + "<td style='text-align: center;' onclick='tdClick(this)' name='num' oninput='numInput(this)'>" + "</td>"
        //规格
        + "<td disabled style='text-align: center;' onclick='tdClick(this)' name='perBox'>" + "</td>"
        //供应商id
        + "<td style='text-align: center;' name='supplierId'>" + $("#add-all-supplierId").val() + "</td>"
        //供应商名称
        + "<td style='text-align: center;' onclick='tdClick(this)' autocomplete='off' name='supplierName'>"
        + $("#add-all-supplierName").val()
        + "</td>"
        //入库成本
        + "<td style='text-align: center;' onclick='tdClick(this)' name='priceYuan'>" + "</td>"
        //备注
        + "<td style='text-align: center;' onclick='tdClick(this)' name='note'>" + $("#add-all-note").val() + "</td>"
        //操作
        + "<td align='center' onclick='trDelete(this)'><button type='button' class='btn btn-xs btn-link' >" + "删除" + "</button></td>"
        + "</tr>");
    table.append(tr);
}

//删除一行
function trDelete(tdObject) {
    row--;
    let td = $(tdObject);
    td.parents("tr").remove();
}

//模糊搜索 输入信息 ，返回符合条件的商品列表
function getAddGoodsData(inputObj) {
    $.get({
        url: "/goods/list",
        data: {
            goodsName: $(inputObj).val()
        },
        success: function (data) {
            let htmlAdd = ''
            data.forEach(function (item) {
                htmlAdd +=
                    `<li>
                            <a id=${item.id} name=${item.goodsName} onclick="chooseAddGoods(id,name,this)" href="javascript:;">${item.goodsName}</a>
                            <a name=${item.perBox} href="javascript:;" display="none"></a>
                         </li>`
            })
            $('#add-goods-dropdown-menu').html(htmlAdd)
            $('#add-goods-dropdown-menu').show()
        }
    });
}

//点击弹出的模糊搜索列表，为当前行填充数据，并隐藏模糊搜索列表
function chooseAddGoods(id, name, tObject) {
    let perBox = $(tObject).next().attr("name")
    let tr = $("#add-goodsName").parent().parent();
    tr.children('[name="goodsId"]').eq(0).html(id);
    tr.children('[name="goodsName"]').eq(0).html(name);
    tr.children('[name="perBox"]').eq(0).html(perBox);
    $('#add-goods-dropdown-menu').hide();
}

//新增时 模糊搜索 输入信息 ，返回符合条件的供应商列表
function getAddSupplierData(inputObj) {
    let input = $(inputObj);
    let ul = input.next();
    $.get({
        url: "/supplier/list",
        data: {
            supplierName: input.val()
        },
        success: function (data) {
            ul.html("");
            data.forEach(function (item) {
                let li = `<li>
                            <a id=${item.id} name=${item.supplierName} onclick="chooseAddSupplier(this)" href="javascript:;">${item.supplierName}</a>
                         </li>`
                ul.append(li);
            });
            ul.show();
        }
    });

}

function chooseAddSupplier(aObj) {
    let input = $(aObj).parent().parent().prev();
    let tag = input.parent().prop('nodeName');
    if (tag == 'TD') {
        input.parent().prev().html($(aObj).attr("id"))
    } else if (tag = 'DIV') {
        input.parent().parent().prev().children("div").children("input").val($(aObj).attr("id"))
    }
    input.val($(aObj).attr("name"));
    $(aObj).parent().parent().hide();
}

//修改时 模糊搜索 输入信息 ，返回符合条件的供应商列表
function getUpdateSupplierData() {
    $.get({
        url: "/supplier/list",
        data: {
            supplierName: $("#update-supplierName").val()
        },
        success: function (data) {
            let htmlAdd = ''
            data.forEach(function (item) {
                htmlAdd +=
                    `<li>
                            <a id=${item.id} name=${item.supplierName} onclick="chooseUpdateSupplier(id,name)" href="javascript:;">${item.supplierName}</a>
                         </li>`

            })
            $('#update-supplier-dropdown-menu').html(htmlAdd)
            $('#update-supplier-dropdown-menu').show()
        }
    });
}

//点击弹出的模糊搜索列表，为当前行填充数据，并隐藏模糊搜索列表
function chooseUpdateSupplier(id, name) {
    $("#update-supplierId").val(id);
    $("#update-supplierName").val(name);
    $('#update-supplier-dropdown-menu').hide();
}

//点击其他位置时，隐藏弹出的模糊搜索列表
document.addEventListener('click', function (e) {//监听页面点击事件
    let screenDoc = document.querySelector('.dropdown-menu');//需要关闭的div
    if (screenDoc && !screenDoc.contains(e.target)) {
        screenDoc.style.display = "none";
    }
}, false);
